package com.zhubayi.shirodb.controller;

import com.zhubayi.shirodb.entity.User;
import com.zhubayi.shirodb.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;


/**
 * @author zhubayi
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("register")
    public String register(User user){
        System.out.println(user);
        try {
            userService.register(user);
            return "redirect:/toLogin";
        }catch (Exception e){
            e.printStackTrace();
            return "redirect:/toRegister";
        }
    }
    @PostMapping("login")
    public String login(String username, String password,String code, HttpSession session){
        //比较验证码
        String codes = (String) session.getAttribute("code");
        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            if (codes.equalsIgnoreCase(code)){
                subject.login(new UsernamePasswordToken(username, password));
                return "redirect:/index";
            }else{
                throw new RuntimeException("验证码错误!");
            }
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户名错误");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
        }
        return "redirect:/toLogin";
    }


}
